import 'package:flustars/flustars.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/LoginTypeEnum.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/extension/global_key_extension.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/mixin/login_page_mixin.dart';
import 'package:tracker/pages/login/model/login_resp.dart';
import 'package:tracker/pages/login/widget/login_form.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:tracker/utils/upgrade_utils.dart';

class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState<LoginPage> createState() => _LoginState();
}

class _LoginState extends ConsumerState<LoginPage> with LoginPageMixin {
  final _loginFormKey = GlobalKey();

  double bottomHeight = 20;

  // 是否同意用户协议
  bool isAgreeProtocol = false;

  @override
  void initState() {
    super.initState();
    //监听Widget是否绘制完毕
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
  }

  @override
  void dispose() {
    super.dispose();
  }

  // Widget绘制完成后的回调
  void _afterLayout(Duration timeStamp) async {
    await UpgradeUtils.initXUpdate();
    Future.delayed(const Duration(milliseconds: 100), () {
      // 获取底部高度
      Size loginFormSize = _loginFormKey.size!;
      final offset = _loginFormKey.position();
      // 屏幕高度 - 登录表单高度 = 底部高度
      setState(() {
        bottomHeight = ScreenUtil.getScreenH(context) - loginFormSize.height - offset!.dy;
      });
    });
    // 清空token
    SpUtil.remove('loginData');
    // 是否记住了密码（rememberPasswordModel仅支持记住设备登录、手机号登录的密码）
    final rememberPasswordModel = SpUtil.getObj('rememberPasswordModel', (v) => RememberPasswordModel().fromJson(v),
        defValue: RememberPasswordModel(rememberPassword: false));
    if (rememberPasswordModel.rememberPassword!) {
      ref.read(rememberPasswordProvider.notifier).state = true;
      ref
          .read(globalStateProvider.notifier)
          .updateLoginType(rememberPasswordModel.loginType! == '4' ? LoginTypeEnum.device : LoginTypeEnum.phone);
    }
  }

  /// 底部
  Widget _buildBottom() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      decoration: const BoxDecoration(),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          // 代理商登录按钮
          Container(
            margin: const EdgeInsets.only(bottom: 16),
            child: GestureDetector(
              onTap: () {
                XLogger.debug('代理商登录');
                if (!isAgreeProtocol) {
                  _showAgreeDialog();
                  return;
                }
                context.pushNamed('agent-login');
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Colors.white.withOpacity(0.15),
                      Colors.white.withOpacity(0.08),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(
                    color: Colors.white.withOpacity(0.3),
                    width: 1,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Text(
                      "代理商登录",
                      style: TextStyle(
                        color: Colors.lightBlue,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(width: 6),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.lightBlue,
                      size: 14,
                    ),
                  ],
                ),
              ),
            ),
          ),
          // 协议区域
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.2),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: Colors.white.withOpacity(0.2),
                width: 1,
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: () {
                    setState(() {
                      isAgreeProtocol = !isAgreeProtocol;
                    });
                  },
                  child: Container(
                    padding: const EdgeInsets.all(2),
                    decoration: BoxDecoration(
                      color: isAgreeProtocol ? AppTheme.themeConfig.primaryColor : Colors.transparent,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: isAgreeProtocol ? AppTheme.themeConfig.primaryColor : Colors.white.withOpacity(0.6),
                        width: 2,
                      ),
                    ),
                    child: Icon(
                      Icons.check,
                      color: Colors.white,
                      size: 14,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Flexible(
                  child: Wrap(
                    alignment: WrapAlignment.center,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      const Text(
                        "阅读并同意",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          context.pushNamed('protocol', queryParameters: {
                            'title': '用户协议',
                            'url': 'https://xjtl.tech/user_agreement/index.html'
                          });
                        },
                        child: Text(
                          "《用户服务协议》",
                          style: TextStyle(
                            color: AppTheme.themeConfig.primaryColor,
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                            decoration: TextDecoration.underline,
                            decorationColor: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      const Text(
                        "和",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          context.pushNamed('protocol', queryParameters: {
                            'title': '隐私政策',
                            'url': 'https://xjtl.tech/privacy_policy/index.html'
                          });
                        },
                        child: Text(
                          "《隐私政策》",
                          style: TextStyle(
                            color: AppTheme.themeConfig.primaryColor,
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                            decoration: TextDecoration.underline,
                            decorationColor: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  /// 登录事件（重命名包装）
  void _handleLogin(LoginFormModel model) async {
    // 重置充值弹窗提示
    hasShowRechargeDialog = false;
    // 用户协议是否同意
    if (!isAgreeProtocol) {
      _showAgreeDialog();
      return;
    }
    XLogger.debug('校验通过，开始登录');
    final rememberPassword = ref.watch(rememberPasswordProvider);

    var loginData = {};
    if (model.loginType == LoginTypeEnum.device) {
      loginData['type'] = '4';
      loginData['username'] = model.imei;
      loginData['password'] = model.imeiPassword;
    } else if (model.loginType == LoginTypeEnum.phone) {
      loginData['type'] = '5';
      loginData['username'] = model.phone;
      loginData['password'] = model.phonePassword;
    }
    ToastUtils.showLoading();
    var res = await post<LoginResp, LoginResp>('/app/user/login', data: loginData, decodeType: LoginResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showToast('登录成功');
        SpUtil.putObject('loginData', resp.data!);
        SpUtil.putBool('isLogin', true);
        ref.read(userTypeProvider.notifier).state = UserTypeEnum.fromValue(resp.data!.type!);
        // 是否记住密码
        final rememberPasswordModel = RememberPasswordModel(rememberPassword: rememberPassword);
        if (rememberPassword) {
          rememberPasswordModel.loginType = loginData['type']!;
          rememberPasswordModel.username = loginData['username']!;
          rememberPasswordModel.password = loginData['password']!;
          SpUtil.putObject('rememberPasswordModel', rememberPasswordModel);
        } else {
          SpUtil.remove('rememberPasswordModel');
        }
        // 登录成功
        _onLoginSucceeded(model);
      } else if (resp.code == 10001) {
        // 未绑定手机号, 跳转到绑定手机号页面
        // 保存设备号
        SpUtil.putString('tempLoginImei', model.imei);
        context.push(RouterManager.bindPhone);
      } else {
        ToastUtils.showToast(resp.msg ?? '登录失败');
      }
      XLogger.debug('登录成功');
    }, failure: (String msg, int code) {
      XLogger.error('登录失败 code: $code msg: $msg');
    });
  }

  void _onLoginSucceeded(LoginFormModel model) {
    ToastUtils.dismissLoading();
    ToastUtils.showSuccess('登录成功');
    SpUtil.putBool('isLogin', true);
    // 延迟1秒跳转
    Future.delayed(const Duration(seconds: 1), () {
      context.go('/');
    });
  }

  /// 显示用户协议弹窗
  _showAgreeDialog() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
            title: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        Colors.orange.shade400.withOpacity(0.15),
                        Colors.orange.shade600.withOpacity(0.05),
                      ],
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.info_outline,
                    color: Colors.orange.shade700,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                const Text(
                  '温馨提示',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ],
            ),
            content: Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text.rich(
                TextSpan(
                  children: [
                    const TextSpan(
                      text: '请阅读并同意',
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 15,
                        height: 1.5,
                      ),
                    ),
                    TextSpan(
                      text: '《用户服务协议》',
                      style: TextStyle(
                        color: AppTheme.themeConfig.primaryColor,
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        height: 1.5,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          context.pushNamed('protocol', queryParameters: {
                            'title': '用户协议',
                            'url': 'https://xjtl.tech/user_agreement/index.html'
                          });
                        },
                    ),
                    const TextSpan(
                      text: '及',
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 15,
                        height: 1.5,
                      ),
                    ),
                    TextSpan(
                      text: '《隐私政策》',
                      style: TextStyle(
                        color: AppTheme.themeConfig.primaryColor,
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        height: 1.5,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          context.pushNamed('protocol', queryParameters: {
                            'title': '隐私政策',
                            'url': 'https://app.ljwl.xyz/html/privacy-policy.html'
                          });
                        },
                    ),
                    const TextSpan(
                      text: '后可继续登录',
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 15,
                        height: 1.5,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                ),
                child: const Text(
                  '取消',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      AppTheme.themeConfig.primaryColor,
                      AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: TextButton(
                  onPressed: () {
                    setState(() {
                      isAgreeProtocol = true;
                    });
                    Navigator.of(context).pop();
                  },
                  style: TextButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                    backgroundColor: Colors.transparent,
                  ),
                  child: const Text(
                    '同意并继续',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      body: Stack(children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/login/bg5.jpeg"),
              fit: BoxFit.cover,
            ),
          ),
        ),
        SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints.expand(
              height: ScreenUtil.getScreenH(context),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // logo
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Image.asset(
                        "assets/images/logo/xjww_logo.png",
                        width: 120,
                        height: 120,
                      ),
                      LoginForm(key: _loginFormKey, callback: _handleLogin),
                    ],
                  ),
                ),
                // SizedBox(height: 28,),
                _buildBottom(),
              ],
            ),
          ),
        ),
      ]),
    );
  }
}

class RememberPasswordModel {
  bool? rememberPassword;
  String? loginType;
  String? username;
  String? password;

  RememberPasswordModel({this.rememberPassword, this.loginType, this.username, this.password});

  toJson() {
    return {
      'rememberPassword': rememberPassword,
      'loginType': loginType,
      'username': username,
      'password': password,
    };
  }

  fromJson(Map<dynamic, dynamic> json) {
    return RememberPasswordModel(
      rememberPassword: json['rememberPassword'],
      loginType: json['loginType'],
      username: json['username'],
      password: json['password'],
    );
  }
}
